package com.jhgsys.internal.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jhgsys.internal.common.entity.BaseEntity;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.system.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.ThreadContext;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

import static org.apache.shiro.SecurityUtils.getSubject;

/**
 * @author fenghaijun
 */
@Slf4j
@Component
public class DefaultDBFieldHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            if (ThreadContext.getSecurityManager() != null) {
                User user = (User) getSubject().getPrincipal();
                Date date = new Date();
                String userName = user.getUserName();
                baseEntity.setCreatedBy(userName);
                baseEntity.setCreatedTime(date);
                baseEntity.setUpdatedBy(userName);
                baseEntity.setUpdatedTime(date);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            Date date = new Date();
            if (ThreadContext.getSecurityManager() != null) {
                if (getSubject() != null && getSubject().getPrincipal() != null) {
                    User user = (User) getSubject().getPrincipal();
                    if (user != null) {
                        String userName = user.getUserName();
                        setFieldValByName("updatedTime", date, metaObject);
                        setFieldValByName("updatedBy", userName, metaObject);
                        if (FebsConstant.INVALID.equals(baseEntity.getDeletedFlg())) {
                            setFieldValByName("deletedTime", date, metaObject);
                            setFieldValByName("deletedBy", userName, metaObject);
                        }
                    }
                }
            }
        }
    }
}
